if(!window.xflib || !window.xflib.client) window.xflib = { client: {} }

xflib.client.ProductModal = class ProductModal {

    static modal() { return document.getElementById('product-modal'); }
    static title() { return xflib.client.ProductModal.modal().querySelector('#modal-title'); }
    static productCodeInput() { return xflib.client.ProductModal.modal().querySelector('#product-code'); }
    static productNameInput() { return xflib.client.ProductModal.modal().querySelector('#product-name'); }

    constructor() {
        this.mode = 'info';
        this.modal = xflib.client.ProductModal.modal();
        this.initializeEventListeners();
    }

    initializeEventListeners() {
        //const modal = xflib.client.ProductModal.modal();
        // 关闭按钮
        xflib.client.ProductModal.modal().querySelectorAll('.modal-close').forEach(btn => {
            btn.addEventListener('click', e => {
                //const modal1 = e.target.closest('.modal');
                if (this.modal) this.modal.style.display = 'none';
            });
        });

        // 取消按钮
        const cancelButton = this.modal.querySelector('#cancel-button');
        cancelButton.addEventListener('click', () => {
            this.closeModal();
        });
        // 保存按钮 
        const saveButton = this.modal.querySelector('#save-button');
        saveButton.addEventListener('click', () => {
            this.saveProduct();
        });
    }

    // 关闭模态框
    closeModal() {
        // const modal = document.getElementById('modal');
        this.modal.style.display = 'none';
    }

    // 打开模态框, mode 为 add 或 edit
    openModal(mode, saveCallback, productCode = null, productName = null, cancelCallback = null) {
        this.mode = mode;

        if(!saveCallback) throw new Error('saveCallback is required');
        if (productCode === 'all') throw new Error('请选择需要编辑的产品');
        this.saveCallback = saveCallback;
        this.cancelCallback = cancelCallback||(()=>{});

       if (mode === 'add') {
            xflib.client.ProductModal.title().textContent = '产品 - 新增';
        } else if (mode === 'edit') {
            xflib.client.ProductModal.title().textContent = '产品 - 编辑';
        } else {
            xflib.client.ProductModal.title().textContent = '产品 - 查看';
        }

        xflib.client.ProductModal.productCodeInput().value = productCode||'';
        xflib.client.ProductModal.productNameInput().value = productName||'';

        this.modal.style.display = 'block';
    }

    // 保存产品数据
    saveProduct() {
        const productCode = xflib.client.ProductModal.productCodeInput().value.trim();
        const productName = xflib.client.ProductModal.productNameInput().value.trim();

        if (!productCode || !productName) {
            alert('产品代码和名称不能为空');
            return;
        }

        this.saveCallback( productCode, productName, this.mode).then(result=>this.closeModal())
    }

}
